package web

import (
	"io/fs"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Config struct {
	Dev bool
}

func CreateWebServer(content fs.FS, config Config) *gin.Engine {

	ginMode := gin.ReleaseMode
	if config.Dev {
		ginMode = gin.DebugMode
	}
	gin.SetMode(ginMode)
	route := gin.Default()
	indexHandler := NewIndexHandler(content, config.Dev)
	initIndexRoute(route, indexHandler)

	apiGroup := route.Group("api")
	{
		apiGroup.GET("/ping", func(ctx *gin.Context) {
			ctx.JSON(200, OkResponse("pong"))
		})
	}

	return route
}

func initIndexRoute(route *gin.Engine, handler *IndexHandler) {
	route.NoRoute(func(ctx *gin.Context) {
		ctx.Writer.WriteHeader(200)
		handler.Index(ctx.Writer)
	})

	route.GET("/", func(ctx *gin.Context) {
		handler.Index(ctx.Writer)
	})

	fsys, _ := fs.Sub(handler.content, "assets")
	route.StaticFS("/assets/", http.FS(fsys))
}
